package org.mainlove.project.web;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.mainlove.project.web.framework.result.ActionForward;

@SuppressWarnings("serial")
public class CoreServlet extends LabsServlet {

	private static final Logger log = Logger.getLogger(CoreServlet.class.getName());

	private org.mainlove.project.web.web.service.Test1Service test1Service = new org.mainlove.project.web.web.service.Test1Service();
	private org.mainlove.project.web.web.service.Test2Service test2Service = new org.mainlove.project.web.web.service.Test2Service();

	@Override
	protected void dispathRequest(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String serviceName = getRequestServiceName(request);
		String method = request.getParameter("method");
		String methodWay = request.getMethod().toUpperCase();

		if (StringUtils.isBlank(serviceName) || StringUtils.isBlank(method)) { 
			response.sendError(404);
		}

		ActionForward actionForward = null;
		JSONObject jsonObject = getRequestJsonObject(request, response);

		if (("test1").equals(serviceName)) {

			if (checkMethod(method, methodWay, "testFoo", "GET")) {
				actionForward = test1Service.testFoo(request, response, jsonObject);
			} else if (checkMethod(method, methodWay, "testTxx", "POST")) {
				actionForward = test1Service.testTxx(request, response, jsonObject);
			} else {
				log.warning(" no methodName=[" + method + "] for service"
						+ " org.mainlove.project.web.web.service.Test1Service");
				response.sendError(404);
				return;
			}
		}

		else if ("test2".equals(serviceName)) {

			if (checkMethod(method, methodWay, "testFoo", "ALL")) {
				actionForward = test2Service.testFoo(request, response, jsonObject);
			} else {
				log.warning(" no methodName=[" + method + "] for service"
						+ " org.mainlove.project.web.web.service.Test2Service");
				response.sendError(404);
				return;

			}

		} else {
			log.warning(" no serviceName=[" + serviceName + "] exist");
			response.sendError(404);
			return;

		}

		if (actionForward == null) {
			throw new Exception("actionForward should not be null -serviceName [" + serviceName
					+ "]-method[" + method + "]");
		}
		actionForward.responseResult(response);

	}

}
